﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Util.Common;
using Util.Redis;
using Util.SystemModel;

namespace App.Controllers
{
    public class LoginController : Controller
    {
        private readonly Util.Interface.System.IUser _user;

        public LoginController(Util.Interface.System.IUser user)
        {
            _user = user;
        }
        // GET: Login
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="ulm"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(UserLoginModel ulm)
        {
            ulm.Password = Helper.MD5Encrypt(Helper.MD5Encrypt(ulm.Password));
            var usermodel = _user.UserLogin(ulm.UserName, ulm.Password);
            if (usermodel != null)
            {
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                       1,
                       usermodel.UserId + "-" + usermodel.UserName,
                       DateTime.Now,
                       DateTime.Now.AddMinutes(30),
                       false,
                      "admin"
                       );
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
                FormsAuthentication.SetAuthCookie(usermodel.UserId + "-" + usermodel.UserName, true);
                return RedirectToAction("Index", "Home");

            }
            else
            {
                ViewBag.ErrorMsg = "用户名或者密码错误";
                return View();
            }
        }
        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginOut()
        {
            System.Web.Security.FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Login");

        }


    }
}